<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>图床网</title>
  <link rel="stylesheet" type="text/css" href="index.css" />
</head>
<body>
<div class="container" ondragover="return false" ondragenter="enter(event)">
<!--  <button onclick="img()">加入图片</button>-->
  <input type="file" accept="image/*" onchange="selectFile(this)"/>
<!--&lt;!&ndash;  <img id="upload" src="/iv3hRi9d27e" />&ndash;&gt;-->
<!--  <div ondragover="return false" ondragenter="enter()">-->
<!--    上传-->
<!--  </div>-->
  <h2>图片：</h2>
<!--  <img id="upload" src="/iv3hRi9d27e" />-->
</div>

<script type="text/javascript" src="https://cdn.staticfile.org/spark-md5/0.0.1/spark-md5.min.js"></script>
<script type="text/javascript">
  var $ = function (path) {
    var q = document.querySelector
    return {
      text(value) {
        if (value) {
          q(path).innerText = value
        } else {
          return q(path).innerText
        }
      },
      html(value) {
        if (value) {
          q(path).innerHTML = value
        } else {
          return q(path).innerHTML
        }
      },
      setAttribute(...args) {
        q(path).setAttribute(...args)
      }
    }
  }

  var f_id = 'ieIQWifvdna'
  var _file
  function img() {
    var img = d.createElement('img')
    img.setAttribute('src', `/${f_id}`)
    d.body.appendChild(img)
  }

  function selectFile(e) {
    var file = e.files[0]
    if (!/^image\/.+/.test(file.type)) {
      alert('文件格式不支持')
      return
    }
    // _file = file
    var blobUrl = URL.createObjectURL(file)

    var reader = new FileReader()
    reader.onload = ev => {
      // console.log()
      const md5 = SparkMD5.hash(reader.result)
      onMD5(md5, file)
    }
    reader.readAsBinaryString(file)

    // $('#upload').setAttribute('src', blobUrl)
    // document.querySelector('#upload').setAttribute('src', blobUrl)
    // console.log($('#upload'))
  }

  function onMD5(md5, file) {
    var fd = new FormData()
    fd.append('file', file)
    fd.append('md5', md5)
    fetch('/upload', {
      method: 'post',
      body: fd,
    }).then(value => value.text())
      .then(id => {
        f_id = id
        var h2 = document.querySelector('h2')
        h2.innerText = `图片地址: ${window.location.origin}/${id}`
      })
  }

  function enter(e) {
    console.log('enter', e)
  }
</script>
</body>
</html>
